<?php
namespace Xianlin\MasterManager\Libraries;

use Xianlin\MasterManager\Models\Master as MasterModel;

class Master
{
    /**
     * 获取列表
     * @param $en_name
     * @return array
     */
    public static function list($en_name): array
    {
        static $masters;
        if(isset($masters[$en_name])){
            return $masters[$en_name];
        }
        if(!$master = MasterModel::where(['en_name' => $en_name])->first()){
            return $masters[$en_name] = [];
        }
        return $masters[$en_name] = $master->data;
    }

    /**
     * 获取值
     * @param $en_name
     * @param $key
     * @param null $default
     * @return mixed|null
     */
    public static function get($en_name, $key, $default = null)
    {
        return self::list($en_name)[$key] ?? $default;
    }

    /**
     * 设置master值
     *
     * @param array $master
     * @return bool
     */
    public static function set(array $master): bool
    {
        list($attributes, $values) = collect($master)->partition(function ($item, $key) {
            return $key==='en_name';
        })->toArray();

        return MasterModel::updateOrCreate($attributes, $values) instanceof MasterModel;
    }
}
